package com.wallace.downloadserver.util.myJson

import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.JsonMappingException
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinFeature
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.wallace.downloadserver.controller.LoginController
import org.slf4j.Logger
import org.slf4j.LoggerFactory

/**
 * @Description:
 * 封装关于json\String互转的方法
 * @author Wallace
 * @Date 2022/1/22 15:12
 */
object JsonUtil {
    private val log: Logger = LoggerFactory.getLogger(LoginController::class.java)

    private val mapper = ObjectMapper().registerModule(KotlinModule.Builder()
            .withReflectionCacheSize(512)
            .configure(KotlinFeature.NullToEmptyCollection, false)
            .configure(KotlinFeature.NullToEmptyMap, false)
            .configure(KotlinFeature.NullIsSameAsDefault, false)
            .configure(KotlinFeature.SingletonSupport, false)
            .configure(KotlinFeature.StrictNullChecks, false)
            .build())

    fun <T> toAny(jsonString: String, classType: Class<T>): T? {
        return try {
            mapper.readValue(jsonString, classType)
        } catch (jpe: JsonProcessingException) {
            log.error(jpe.toString())
            null
        } catch (jme: JsonMappingException) {
            log.error(jme.toString())
            null
        }
    }

    fun toJson(any: Any): String? {
        return try {
            mapper.writeValueAsString(any)
        } catch (e: JsonProcessingException) {
            log.error(e.toString())
            null
        }
    }
}